package com.atguigu.gmall.common.interceptors;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.util.UserAuthUtils;
import com.atguigu.gmall.user.vo.UserAuthInfoVo;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author lfy
 * @Description 透传用户头信息；
 * 把老请求（网关传下来的）的用户id/tempId请求头中的东西放到新请求中
 * @create 2022-10-17 11:49
 */
@Slf4j
@Component
public class UserHeaderAuthFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
        log.info("user信息 feign拦截器开始：");
        //以当前线程作为key，从共享的数据里面拿到老请求
//        HttpServletRequest request = CartController.requestMap.get(Thread.currentThread());
//        HttpServletRequest request = CartController.threadLocal.get();

        //SpringMVC随时获取老请求的代码；获取到当前线程绑定的老请求
//        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
//
//        HttpServletRequest request = attributes.getRequest();
//        //从网关放行来的老请求中获取到之前的id
//        String userId = request.getHeader(RedisConst.USER_ID_HEADER);
//        String userTempId = request.getHeader(RedisConst.USER_TEMP_ID_HEADER);

        //从网关放行来的老请求中获取到之前的id
        UserAuthInfoVo info = UserAuthUtils.getUserAuthInfo();

        if(info != null){
            if(info.getUserId()!=null){
                template.header(RedisConst.USER_ID_HEADER,info.getUserId().toString());
            }
            template.header(RedisConst.USER_TEMP_ID_HEADER,info.getUserTempId());
        }
    }
}
